import axios, {AxiosRequestConfig, AxiosResponse, AxiosInstance, AxiosStatic} from 'axios';
import { ElNotification } from 'element-plus'
import {Router, useRouter} from 'vue-router';
class AxiosUtilt{
    public requests: AxiosInstance;
    public router: Router;
    
    constructor(axios: AxiosStatic){
      this.router = useRouter();
      this.requests = axios.create({
        // baseURL: 'http://127.0.0.1:8081',
        // baseURL: 'https://www.markerhub.com/vueadmin-java',
        baseURL: '/mock',
        timeout: 5000,
        headers:{
          "Content-Type": "application.json; charset=utf-8"
        }
      })
    }

    /**
     * 获取请求拦截器
     * @param requests 
     */
    requestInterceptors(requests: AxiosInstance) {
      this.requests.interceptors.request.use(
        (config: any)=>{
          console.log('我是拦截器,请求发送成功');
          config.headers['Authorization'] = localStorage.getItem("token");
          return config
        })
      }
    
    /**
     * 获取响应拦截器
     * @param requests 
     */
    responseInterceptors(requests: AxiosInstance){
      requests.interceptors.response.use(
        (response: AxiosResponse)=>{
          console.log('我是拦截器，获取响应成功');
          let res = response.data

          if(res.code === 200){
            ElNotification({
              title: 'Success',
              message: res.msg,
              type: 'success',
            })
            return response

          }else{

            ElNotification({
              title: 'Error',
              message: res.msg || '未知错误',
              type: 'error',
            })
            return Promise.reject(response.data.msg)
            
          }
        },
        (error: any)=>{

          if(error.response.data){
            error.massage = error.response.data.msg
          }

          if(error.response.state === 401){
            this.router.push('/')
          }

          ElNotification({
            title: 'Error',
            message: error.massage || '未知错误',
            type: 'error',
          })

          return Promise.reject(error)
        }
      )
    }

    /**
     * 
     * @returns 获取axios实例对象
     */
    getRequest(){
      this.requestInterceptors(this.requests)
      this.responseInterceptors(this.requests)
      return this.requests
  }
}

/**
 * 暴露axios
 */
export default new AxiosUtilt(axios).getRequest() 